package com.alit.ibot.robot.wechat.util;

import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alit.ibot.robot.projectvariable.PVK;
import com.alit.ibot.robot.projectvariable.ProjectVariableUtil;
import com.alit.ibot.robot.wechat.data.AccessToken;
import com.litong.utils.http.commonshttpclient.HttpClientUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信通用工具类
 */
@Slf4j
public class WechatAccessTokenUtil {
  // 凭证获取（GET）
  public final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
  private static long expiresTime; // access_token过期时间
  private static AccessToken accessToken = null;

  /**
   * 设置access_token更新过期时间
   */
  public static void updateExpiresTime(int expiresIn) {
    /**
     * expiresIn时间是秒,经过改秒之后,access_token会过期
     */
    expiresTime = System.currentTimeMillis() + expiresIn * 1000;
  }

  /**
   * 判断token是否过期,过期返回true
   * 
   * @return
   */
  public static boolean isAccessTokenExpired() {
    return System.currentTimeMillis() > expiresTime;
  }

  /**
   * 获取微信接口访问凭证
   * 
   * @return
   */
  public static String getAccessToken(String appid, String secret) {
    String requestUrl = TOKEN_URL.replace("APPID", appid).replace("APPSECRET", secret);
    // 发起GET请求获取凭证
    String result = HttpClientUtil.get(requestUrl);
    JSONObject jsonObject = JSON.parseObject(result);
    if (null != jsonObject) {
      try {
        accessToken = new AccessToken();
        int expiresIn = jsonObject.getInteger("expires_in");
        updateExpiresTime(expiresIn); // 更新过期时间
        accessToken.setExpiresIn(expiresIn);
        accessToken.setAccessToken(jsonObject.getString("access_token"));
      } catch (Exception e) {
        e.printStackTrace();
        // 获取token失败
        log.error("返回的信息:" + result);
      }
    }
    return accessToken.getAccessToken();
  }

  public static String getAccessToken() {
    String appId = ProjectVariableUtil.getValue(PVK.wechatAppId);
    String appSecret = ProjectVariableUtil.getValue(PVK.wechatSecret);
    if (isAccessTokenExpired()) { // 获取新的access_token 并返回
      String accessToken = WechatAccessTokenUtil.getAccessToken(appId, appSecret);
      return accessToken;
    } else {// 返回上次获取的access_token
      return accessToken.getAccessToken();
    }
  }

  /**
   * URL编码（utf-8）
   * 
   * @param source
   * @return
   */
  public static String urlEncodeUTF8(String source) {
    String result = source;
    try {
      result = java.net.URLEncoder.encode(source, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return result;
  }

  /**
   * 根据内容类型判断文件扩展名
   * 
   * @param contentType
   *          内容类型
   * @return
   */
  public static String getFileExt(String contentType) {
    String fileExt = "";
    if ("image/jpeg".equals(contentType))
      fileExt = ".jpg";
    else if ("audio/mpeg".equals(contentType))
      fileExt = ".mp3";
    else if ("audio/amr".equals(contentType))
      fileExt = ".amr";
    else if ("video/mp4".equals(contentType))
      fileExt = ".mp4";
    else if ("video/mpeg4".equals(contentType))
      fileExt = ".mp4";
    return fileExt;
  }
}
